<script>
export default {
  name: 'AppForm'
}
</script>

<script setup>
import { reactive, watch } from 'vue'

const props = defineProps({
  items: {
    type: Array,
    default: () => []
  },
  labelWidth: {
    type: String,
    default: '70px'
  }
})

// eslint-disable-next-line vue/require-prop-types
const model = defineModel({ default: () => ({}) })

// const emits = defineEmits(['submit'])

const form = reactive({})
props.items.map(({ key, component }) => {
  switch (component) {
    case 'el-checkbox-group':
      form[key] = []
      break
    case 'el-input-tag':
      form[key] = []
      break
    case 'el-switch':
      form[key] = false
      break
    case 'el-input-number':
      form[key] = 0
      break
    default:
      form[key] = ''
  }
})

watch(
  form,
  () => {
    Object.assign(model.value, form)
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => model.value,
  () => {
    Object.assign(form, model.value)
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <el-form :model="form" :label-width="labelWidth">
    <template v-for="i in items" :key="i.key">
      <el-form-item :label="i.label">
        <template #default>
          <component :is="i.component" v-model="form[i.key]" v-bind="i.props">
            <template v-if="i.component === 'el-select'">
              <el-option v-for="option in i.options" v-bind="option" :key="option.value" />
            </template>
            <template v-else-if="i.component === 'el-checkbox-group'">
              <el-checkbox v-for="option in i.options" v-bind="option" :key="option.value" />
            </template>
            <template v-else-if="i.component === 'el-radio-group'">
              <el-radio v-for="option in i.options" v-bind="option" :key="option.value" />
            </template>
            <template #suffix>
              <span v-if="i.suffix">{{ i.suffix }}</span>
            </template>
          </component>
          <el-alert v-if="i.tip" :title="i.tip" type="info" :closable="false" class="mt-1" />
        </template>
      </el-form-item>
    </template>
    <el-form-item>
      <slot></slot>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
:deep(.el-form-item__content) {
  width: 100%;
  justify-content: end;
  //margin-right: 10px;
}
</style>
